//
//  BandDeviceVC.m
//  KEREN
//
//  Created by MW on 2023/3/17.
//

#import "BandDeviceVC.h"
#import "DeviceInfo.h"
@interface BandDeviceVC ()
@property (nonatomic, strong) UILabel *deviceNameLbl;
@property (nonatomic, strong) UILabel *deviceCodeLbl;
@property (nonatomic, strong) UIImageView *deviceIcon;
@property (nonatomic, strong) DeviceInfo *deviceInfo;
@end

@implementation BandDeviceVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"扫描结果"];
    [self requestDeviceInfoBySN];
}

- (void)requestDeviceInfoBySN{
    WEAKSELF
    [NetworkingTool POST:Device_onfo_bySN parameters:@{@"sn_code":_snCode} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if ([response[@"code"]  intValue] == 0) {
            if(response[@"data"] && [response[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dict = response[@"data"];
                weakSelf.deviceInfo = [DeviceInfo initWithDictionary:dict];
                [weakSelf setViewLayout];
            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

-(void)setViewLayout{
    UIView *deviceView = [[UIView alloc] initWithFrame:CGRectMake(0, NAVTOP_Height, DEVICE_WIDTH, 100)];
    deviceView.backgroundColor = Whire_Color;
    [self.view addSubview:deviceView];
    _deviceIcon = [[UIImageView alloc] initWithFrame:CGRectMake(24, 20, 60, 60)];
    [deviceView addSubview:_deviceIcon];
    _deviceNameLbl = [UILabel setLblText:@"" font:Font(24) withColor:Black_Color inSubView:deviceView];
    [_deviceNameLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_deviceIcon.mas_right).offset(12);
        make.top.offset(22);
        make.height.offset(32);
        make.right.offset(-124);
    }];
    _deviceCodeLbl = [UILabel setLblText:@"" font:Font(12) withColor:Color_86898E inSubView:deviceView];
    [_deviceCodeLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_deviceIcon.mas_right).offset(12);
        make.bottom.offset(-22);
    }];
    
    UIButton *scanBtn = [UIButton setButtonWithTitle:@"重新扫码" titleColor:Whire_Color titleFont:BFont(16) cornerRadius:25 backColor:Color_7ACC00];
    [self.view addSubview:scanBtn];
    if(_isFromBLEVC){
        [scanBtn setTitle:@"重新扫描" forState:UIControlStateNormal];
    }
    scanBtn.frame = CGRectMake(24, DEVICE_HEIGHT - BottomSpance_height - 58, DEVICE_WIDTH - 48, 58);
    [scanBtn addTarget:self action:@selector(gobackScan) forControlEvents:UIControlEventTouchUpInside];
    CGFloat btnWidth;
    UIButton *bindBtn;
    if(!_deviceInfo.is_bind){
        btnWidth = [@"立即绑定" boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:Font(16)} context:nil].size.width;
        bindBtn = [UIButton setButtonWithTitle:@"立即绑定" titleColor:Color_7ACC00 titleFont:Font(16) cornerRadius:18 backColor:[UIColor clearColor]];
        bindBtn.layer.borderWidth = 1;
        bindBtn.layer.borderColor = Color_7ACC00.CGColor;
        [bindBtn addTarget:self action:@selector(bindDevice) forControlEvents:UIControlEventTouchUpInside];
    }else{
        btnWidth = [@"已绑定" boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:Font(16)} context:nil].size.width;
        bindBtn = [UIButton setButtonWithTitle:@"已绑定" titleColor:Whire_Color titleFont:Font(16) cornerRadius:18 backColor:Color_7ACC00];
        bindBtn.layer.borderWidth = 1;
        bindBtn.layer.borderColor = Color_borderColor;
    }
    [deviceView addSubview:bindBtn];
    [bindBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 15, 0, 15)];
    [bindBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-24);
        make.height.offset(36);
        make.top.offset(32);
        make.width.offset(btnWidth + 30);
    }];
    if(_deviceInfo.frame_code.length > 4){
        _deviceCodeLbl.text = [NSString stringWithFormat:@"车架号后四位：%@",[_deviceInfo.frame_code substringFromIndex:_deviceInfo.frame_code.length - 4]];
    }
    [_deviceIcon sd_setImageWithURL:[NSURL URLWithString:_deviceInfo.photo] placeholderImage:[UIImage imageNamed:@"devcie_defalaut_icon"] options:SDWebImageRefreshCached];
    _deviceNameLbl.text = _deviceInfo.name;

}

- (void)bleAuthentication{
    WEAKSELF
    [[KRAlartManager shareInstance] showLodingAlertView:@"连接中..."];
    [[HABleManager sharedManager] connectToPeripheral:self.peripheral success:^(CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral) {
        DDLogInfo(@"连接成功");
        peripheral.snCode = weakSelf.snCode;
    } fail:^(CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral, NSError * _Nonnull error) {
        [[KRAlartManager shareInstance] hidenLodingImageView];
        [[KRAlartManager shareInstance] showAlert:@"请前往设置查看是否已配对并忽略"];
    } characteristic:^(CBPeripheral * _Nonnull CBPeripheral, CBService * _Nonnull service, NSError * _Nonnull error) {
        [[KRAlartManager shareInstance] hidenLodingImageView];
    }];

}

- (void)gobackScan{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)bindDevice{
    WEAKSELF
    [NetworkingTool POST:Device_bind parameters:@{@"sn_code":_snCode} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if(weakSelf.isFromBLEVC){
                [self bleAuthentication];
            }
            [[NSNotificationCenter defaultCenter]postNotificationName:@"UPDATECURRENTDEVICE" object:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[KRAlartManager shareInstance] showImageAlert:@"绑定成功！" ishaveBtn:NO btnTitle:@"" decLbl:@"返回首页（3S）" withImageStr:@"success_img" isDown:YES WithDownCount:3 sucessBlock:^(BOOL isSucess){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                    });
                }];
            });
        }
        
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
    }];
}

@end
